package com.youxuan.filter;

import com.youxuan.enums.AppHttpCodeEnum;
import com.youxuan.exception.SystemException;
import com.youxuan.pojo.entity.LoginUser;
import com.youxuan.util.JwtUtil;
import com.youxuan.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        if (httpServletRequest.getMethod().equals("OPTIONS")){
            httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
            httpServletResponse.setHeader("Access-Control-Allow-Headers","*");
            httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        String id;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            id = claims.getSubject();
        } catch (Exception e) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        LoginUser loginUser = redisCache.getCacheObject("youxuan:"+id);
        if (Objects.isNull(loginUser)){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }
}
